<?php

class DefaultController extends Controller
{
	public function actionSetFeatured($id)
	{
		$model = News::model()->findByPk($id);

		if (!empty($model)) {
			$model->updateByPk($id, array('featured'=>'Y'));
		}

		$this->redirect(array('/News/default/index'));
	}

	public function actionRemoveFeatured($id)
	{
		$model = News::model()->findByPk($id);

		if (!empty($model)) {
			$model->updateByPk($id, array('featured'=>'N'));
		}

		$this->redirect(array('/News/default/index'));
	}

	public function actionIndex()
	{
		$model=new News('search');
		$model->unsetAttributes();
		if(isset($_GET['News']))
			$model->attributes=$_GET['News'];

		$this->render('index', array(
			'model'=>$model
		));
	}

	public function actionView($id)
	{
		$model = $this->loadModel($id);
		$model->content = str_replace('<img src="/images/news/', '<img src="' . IMAGES_URL . 'news/', $model->content);

		$this->render('view',array(
			'model'=>$model,
		));
	}

	public function actionCreate()
	{
		$model=new News('create');

		if(isset($_POST['News']))
		{
			$model->attributes=$_POST['News'];
			$model->slug = $this->createSlug($model->title);
			$model->posteddate = $model->updatedate = date('Y-m-d H:i:s');

			// Save news image
			$imagePath = IMAGES_DIR . 'news/' . date('Ymd', strtotime($model->posteddate)) . '/';
			$imageUploadFile	= CUploadedFile::getInstance($model, 'image');
			if ($imageUploadFile !== null) {
				$model->image = $model->slug . '.' . $imageUploadFile->extensionName;
				if (!file_exists($imagePath)) {
					mkdir($imagePath, 0777, true);
				}
				$imageUploadFile->saveAs($imagePath . $model->image);
				// Resize images
				$this->resizeNewsImage($imagePath, $model->image, date('Y-m-d H:i:s'));
			}

			// Convert all images & save to the project in content
			/*
			preg_match_all('/\<img(.*)src\=\"([^\"]+)\"(.*)\>/', $model->content, $matches, PREG_SET_ORDER);

			foreach ($matches as $key => $images) {
				// Save images
				$filePath = pathinfo($images[2]);
				$imageName = $model->slug . '_' . ($key + 1) . '.' . $filePath['extension'];
				$fp = fopen($imagePath . $imageName, 'wb');
				fclose($fp);
				copy($images[2], $imagePath . $imageName);
				// Replace in content
				$model->content = str_replace($images[0], '<img src="/images/news/' . date('Ymd', strtotime($model->posteddate)) . '/' . $imageName . '" alt="' . $model->title . '" /><br />', $model->content);
			}
			*/
			// Save news
			if($model->save())
				$this->redirect(array('view', 'id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$model->content = str_replace('<img src="/images/news/', '<img src="' . Yii::app()->createAbsoluteUrl('/') . '/images/news/', $model->content);
		$model->content = str_replace('/backend/images/news/', '/images/news/', $model->content);

		if(isset($_POST['News']))
		{
			$model->attributes=$_POST['News'];
			$model->slug = $this->createSlug($model->title);
			$model->updatedate = date('Y-m-d H:i:s');

			// Save news image
			$imagePath = IMAGES_DIR . 'news/' . date('Ymd', strtotime($model->posteddate)) . '/';
			$imageUploadFile	= CUploadedFile::getInstance($model, 'image');
			if ($imageUploadFile !== null) {
				$model->image = $model->slug . '.' . $imageUploadFile->extensionName;
				// Dont need to create folder because it's always exist
				if (!file_exists($imagePath)) {
					mkdir($imagePath, 0777, true);
				}
				$imageUploadFile->saveAs($imagePath . $model->image);
				// Resize images
				$this->resizeNewsImage($imagePath, $model->image, date('Y-m-d H:i:s'));
			}
			/*
			// Convert all images & save to the project in content
			preg_match_all('/\<img(.*)src\=\"([^\"]+)\"(.*)\>/', $model->content, $matches, PREG_SET_ORDER);

			foreach ($matches as $key => $images) {
				// Save images
				$filePath = pathinfo($images[2]);
				$localPath = IMAGES_URL . 'news/' . date('Ymd', strtotime($model->posteddate));
				$imageName = $filePath['filename'] . '.' . $filePath['extension'];
				echo $filePath['dirname'] . ' - ' . $localPath;
				echo "<br />";
				if ($filePath['dirname'] !== $localPath) {
					$imageName = $model->slug . '_' . ($key + 1);
					while (file_exists($imagePath . '.' . $filePath['extension'])) {
						$imageName .= 'nte';
					}
					$imageName .= '.' . $filePath['extension'];
					$fp = fopen($imagePath . $imageName, 'wb');
					fclose($fp);
					copy($images[2], $imagePath . $imageName);
				}
				// Replace in content
				$model->content = str_replace($images[0], '<img src="/images/news/' . date('Ymd', strtotime($model->posteddate)) . '/' . $imageName . '" alt="' . $model->title . '" /><br />', $model->content);
			}
			*/
			if($model->save()) {
				$this->redirect(array('view', 'id'=>$model->id));
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	public function loadModel($id)
	{
		$model=News::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
}